package com.example.user.broadcastjava;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/*BroadCast in xml（3.1）与BroadCast in java（3.2）的区别：
        用manifest方法进行注册之后，无论应用程序没有启动，或者已经被关闭，这个BroadcastReceiver依然会继续运行（都处于活动状态），这样的运行机制都可以接受到广播。
        在代码中进行注册和反注册时，在启动Activity注册，在Activity不可见时取消注册。这样可以节省cpu电源和运行时间。
*/


public class BroadCastJavaActivity extends AppCompatActivity {

    private Button registerButton = null;
    private Button unregisterButton = null;
    private SMSReceiverActivity smsReceiver = null;

    private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.broadcast_java);

        registerButton = (Button)findViewById(R.id.register);
        registerButton.setOnClickListener(new RegisterReceiverListener());
        unregisterButton = (Button)findViewById(R.id.unregister);
        unregisterButton.setOnClickListener(new UnRegisterReceiverListener());

    }

    class RegisterReceiverListener implements OnClickListener{

        @Override
        public void onClick(View v) {
            //生成一个BroiadcastReceiver对象
            smsReceiver = new SMSReceiverActivity();
            //生成一个IntentFilter对象,注册广播接收器
            IntentFilter filter = new IntentFilter();
            //为IntentFilter添加一个Action
            filter.addAction(SMS_ACTION);
            //将BroadcastReceiver对象注册到系统当中
        BroadCastJavaActivity.this.registerReceiver(smsReceiver, filter);
        }
    }

    class UnRegisterReceiverListener implements OnClickListener{

        @Override
        public void onClick(View v) {
        //注销广播接收器
            BroadCastJavaActivity.this.unregisterReceiver(smsReceiver);
        }
    }
}
